<template>
    <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="ruleFormRef">
        <el-form-item label="名称：" prop="user">
            <el-input v-model="formInline.user" placeholder="请输入用户名" />
        </el-form-item>
        <div class="block">
            <el-form-item prop="region">
                <span class="demonstration">创建时间：</span>
                <el-date-picker v-model="formInline.region" type="daterange" range-separator="～"
                    start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" />
            </el-form-item>
        </div>
        <el-form-item>
            <el-button type="primary" @click="search()">搜索</el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
    </el-form>
    <div class="botton-group">

        <el-button type="primary" plain @click="addOne(),resetForm1(ruleFormRef1)">新增</el-button>
        <!-- <el-button plain @click="delect()">删除</el-button> -->
        <el-button plain>更多操作</el-button>
    </div>
    <el-table ref="multipleTableRef" :data="state.deptData" style="width: 100%" row-key="key" :tree-props="defaultProps"
        @selection-change="handleSelectionChange" :default-sort="{ prop: 'date', order: 'descending' }">
        <el-table-column type="selection" width="55" />
        <el-table-column property="title" label="名称" width="120" />
        <el-table-column property="value" label="排序" show-overflow-tooltip sortable width="100" />
        <el-table-column property="createTime" label="创建时间" show-overflow-tooltip />
        <el-table-column property="modifyTime" label="修改时间" show-overflow-tooltip>
            <template #default="scope">{{scope.row.modifyTime==null?'从未修改': scope.row.modifyTime}}</template>
        </el-table-column>
        <el-table-column prop="text" label="操作" fixed="right">
            <template #default="scope">
                <el-button :icon="Edit" circle @click="handleEdit(scope.$index, scope.row)" />
            </template>
        </el-table-column>>
    </el-table>

    <div class="demo-pagination-block">
        <el-pagination v-model:currentPage="currentPage4" v-model:page-size="pageSize4" :page-sizes="[10, 20, 30, 40]"
            :small="small" :disabled="disabled" :background="background" :total="state.page"
            layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </div>

    <el-dialog v-model="dialogTableVisible" :title="state.changeoradd">
        <el-form :model="form1" ref="ruleFormRef1">
            <el-form-item label="部门名称：" :label-width="formLabelWidth" prop="deptName">
                <el-input v-model="form1.deptName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="菜单排序：" style="margin-left: 57px;" prop="orderNum">
                <el-input-number v-model="form1.orderNum" class="mx-4" :min="1" controls-position="right"
                    @change="handleChange" />
            </el-form-item>
            <div class="account-list">
                <div>
                    <p style="margin: 10px 10px;">上级部门：</p>
                    <el-tree :data="state.deptData" :props="defaultProps1" show-checkbox check-strictly ref="treeRef"
                        node-key="key" style="overflow-y: auto;height: 130px;">
                    </el-tree>
                </div>
            </div>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="primary" @click="realGo()">提交</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible" title="删除确认" width="30%">
        <span>你确定要删除以下部门吗？
            <p style="margin-top: 10px;">{{state.delname.toString()}}</p>
        </span>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="realDel()">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { FormInstance, ElTable, ElTree, ElMessage } from 'element-plus'
import {
    Edit,
} from '@element-plus/icons-vue'
import { getDeptApi, addDeptApi, changeDeptApi, delDeptApi } from '../../apis/dept'

interface User {
    date: string
    name: string
    address: string
}
const treeRef = ref<InstanceType<typeof ElTree>>()
const ruleFormRef = ref<FormInstance>()
const ruleFormRef1 = ref<FormInstance>()
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<User[]>([])
const formInline = reactive({
    user: '',
    region: '',
})
const dialogTableVisible = ref(false)
const innerVisible1 = ref(false)
const dialogVisible = ref(false)
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const formLabelWidth = '140px'

const state = reactive({
    deptData: [] as any,
    menuData: [] as any,
    changeoradd: '',
    delId: '',
    delname: '',
    pageSize: 10,
    pageNum: 10,
    page: 1,

})

const resetForm = (ruleForm: FormInstance | undefined) => {
    if (!ruleForm) return;
    ruleForm.resetFields();
    getDept()
};

const resetForm1 = (ruleForm: FormInstance | undefined) => {
    if (!ruleForm) return;
    ruleForm.resetFields();
    // getAllRole()
};

const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
}

const form1 = reactive({
    deptName: '',
    orderNum: '' as any,
    parentId: '' as any,
    deptId: '' as any,
})

const getCheckedKeys = () => {
    console.log(treeRef.value!.getCheckedKeys(false))
    form1.parentId = treeRef.value!.getCheckedKeys(false)
}

function search() {
    const a = `deptName=${formInline.user}&createTimeFrom=${formInline.region[0]}&createTimeTo=${formInline.region[1]}&`
    console.log(typeof formInline.user);
    getDept(a)


}

function delect() {
    const data = JSON.parse(JSON.stringify(multipleSelection.value));
    console.log(data);
    const a = data.map((item: { title: any }) => {
        return item.title
    })
    state.delId = a
    const b = data.map((item: { id: any }) => {
        return item.id
    })
    state.delname = a
    state.delId = b
    console.log(a);
    console.log(b);
    if (data != "") {
        dialogVisible.value = true
    } else {
        ElMessage.error("没有选中任何内容，无法删除")
    }


}

const handleChange = (value: number) => {
    console.log(value)
}

const defaultProps1 = {
    children: state.deptData,
    label: "title"
}

const handleEdit = (index: number, row: any) => {
    console.log(index, row)
    state.changeoradd = "修改部门"
    dialogTableVisible.value = true
    form1.deptName = row.title
    form1.orderNum = Number(row.value)
    form1.parentId = row.parentId
    form1.deptId = row.value
    setCheckedKeys((form1.parentId).split())
    console.log((form1.parentId).split());

}

const defaultProps = {
    children: state.deptData.children,
    hasChildren: "true"
}

const setCheckedKeys = (data: any) => {
    treeRef.value!.setCheckedKeys(data, false)
}

const resetChecked = () => {
    treeRef.value!.setCheckedKeys([], false)
}

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    state.pageSize = val
    console.log(state.pageSize);
    getDept(`pageSize=${val}`)
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    state.pageNum = val
    getDept(`pageNum=${val}`)
}

async function getDept(data?: any) {
    const res = await getDeptApi(data)
    console.log(res.rows.children);
    state.deptData = res.rows.children
    console.log(state.deptData);
    state.page = res.rows.children.length


}

async function addDept() {
    const a = `deptName=${form1.deptName}&orderNum=${form1.orderNum}&parentId=${form1.parentId}`
    const res = await addDeptApi(a)
    console.log(res);
    if (res == "") {
        ElMessage.success("添加部门成功")
        getDept(`pageNum=${state.pageNum}&pageSize=${state.pageSize}`)
        dialogTableVisible.value = false
    }

}
async function changeDept() {
    const a = `deptName=${form1.deptName}&orderNum=${form1.orderNum}&parentId=${form1.parentId}&deptId=${form1.deptId}`
    const res = await changeDeptApi(a)
    console.log(res);
    if (res == "") {
        ElMessage.success("修改部门成功")
        getDept(`pageNum=${state.pageNum}&pageSize=${state.pageSize}`)
        dialogTableVisible.value = false
    }

}

async function delOne() {
    const res = await delDeptApi(state.delId)
    console.log(res);
    if (res == "") {
        ElMessage.success("删除部门成功")
        getDept(`pageNum=${state.pageNum}&pageSize=${state.pageSize}`)
        dialogTableVisible.value = false
    }
}
function addOne() {
    state.changeoradd = "新增部门"
    dialogTableVisible.value = true

}

function realGo() {
    getCheckedKeys()
    console.log(`deptName=${form1.deptName}&orderNum=${String(form1.orderNum)}&parentId=${form1.parentId}`);
    if (state.changeoradd == "新增部门") {
        addDept()
    } else {
        changeDept()
    }
}

function realDel() {
    dialogVisible.value = false
    delOne()

}

onMounted(() => {
    getDept()
})
</script>

<style scoped>
.demo-form-inline {
    display: flex;
}

.el-dropdown-link {
    margin-right: 10px;
}

.account-list {
    margin-left: 49px;
}

.el-input-number {
    width: 100%;
}

.demo-pagination-block {
    margin: 15px 0;
}
.botton-group{
    margin-bottom: 10px;
}
</style>